/**
 * 
 */
package com.arx.graphics;

import com.arx.common.GlobalConsts;
import com.arx.graphics.flyweight.ANIM_HANDLE;
import com.arx.graphics.flyweight.ANIM_USE;
import com.dalonedrau.d20.Diceroller;

/**
 * @author Donald
 */
public class Animation {
	/** the singleton instance. */
	private static Animation	instance;
	/**
	 * Gets the one and only instance of {@link Animation}.
	 * @return {@link Animation}
	 */
	public static Animation getInstance() {
		if (Animation.instance == null) {
			Animation.instance = new Animation();
		}
		return Animation.instance;
	}
	private short	anim_power[]	= {
									100, 20, 15, 12, 8, 6, 5,
									4, 3, 2, 2, 1, 1, 1, 1
									};
	private short ANIM_GetAltIdx(final ANIM_HANDLE ah, final long old) {
		short val = 0;
		if (ah.getAlt_nb() != 1) {
			float tot = anim_power[0];
			for (short i = 1; i < ah.getAlt_nb(); i++) {
				tot += anim_power[Math.min(i, 14)];
			}
			boolean notDone = true;
			while (notDone) {
				for (short i = 1; i < ah.getAlt_nb(); i++) {
					float rnd = Diceroller.getInstance().ARXRnd() * tot;
					if (rnd < anim_power[Math.min(i, 14)]
							&& i != old) {
						val = i;
						notDone = false;
						break;
					}
				}
			}
		}
		return val;
	}
	public void ANIM_Set(final ANIM_USE au, final ANIM_HANDLE anim) {
		if (au != null
				&& anim != null) {
			au.setCur_anim(anim);
			au.setAltidx_cur(ANIM_GetAltIdx(anim, au.getAltidx_cur()));
			if (au.getAltidx_cur() > au.getCur_anim().getAlt_nb()) {
				au.setAltidx_cur((short) 0);
			}
			au.setCtime(0);
			au.setLastframe(-1);
			au.removeFlag(GlobalConsts.EA_PAUSED);
			au.removeFlag(GlobalConsts.EA_ANIMEND);
			au.removeFlag(GlobalConsts.EA_LOOP);
			au.removeFlag(GlobalConsts.EA_FORCEPLAY);
		}
	}
}
